package com.train.openfeign.core.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.train.common.enums.impl.BizExceptionEnums;
import com.train.common.enums.impl.SysExceptionEnums;
import com.train.common.exception.GlobalException;
import com.train.common.resp.CommonResp;
import com.train.common.status.HttpStatus;

import java.util.ArrayList;
import java.util.List;

public class OpenFeignUtils {

    public static <T> T getResult(CommonResp resp, Class<T> clazz) {
        //请求是否成功
        if (!resp.get(CommonResp.CODE_TAG).equals(HttpStatus.SUCCESS)) {
            throw new GlobalException(getMessage(resp));
        }

        //是否获取到目标结果数据
        Object object = resp.get(CommonResp.DATA_TAG);
        if (ObjectUtil.isEmpty(object)) {
            throw new GlobalException(SysExceptionEnums.EXP_SERVER);
        }

        return BeanUtil.copyProperties(object, clazz);
    }

    public static <T> List<T> getResultList(CommonResp resp, Class<T> clazz) {
        //请求是否成功
        if (!resp.get(CommonResp.CODE_TAG).equals(HttpStatus.SUCCESS)) {
            throw new GlobalException(getMessage(resp));
        }

        //是否获取到目标结果数据
        Object object = resp.get(CommonResp.DATA_TAG);
        if (!(object instanceof List<?> list) || CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }

        return BeanUtil.copyToList(list, clazz);
    }

    //请求是否成功
    public static boolean isSuccess(CommonResp resp) {
        Object object = resp.get(CommonResp.CODE_TAG);
        if (object == null) {
            throw new GlobalException(SysExceptionEnums.EXP_SERVER);
        }
        if (!(object instanceof Integer code)) {
            throw new GlobalException(SysExceptionEnums.EXP_SERVER);
        }

        return code == HttpStatus.SUCCESS;
    }

    public static String getMessage(CommonResp resp) {
        if (ObjectUtil.isNull(resp)) {
            return SysExceptionEnums.EXP_SERVER.getMessage();
        }
        Object msg = resp.get(CommonResp.MESSAGE_TAG);
        if (resp.get(CommonResp.CODE_TAG).equals(HttpStatus.SUCCESS)) {
            return msg != null ? msg.toString() : StrUtil.EMPTY;
        }
        return msg != null ? msg.toString() : SysExceptionEnums.EXP_SERVER.getMessage();
    }
}
